import {
  clone
} from '@shared';
// 查找页面是否是 tabBar 页面
export function findTabBarIndex(pagePath, tabBarList) {
  if (!tabBarList) {
    return -1;
  }
  return tabBarList.findIndex(item => {
    if (typeof item === 'string') {
      return item === pagePath;
    } else {
      return item.pagePath === pagePath;
    }
  });
}
// tabBar
export function formatTabBar(tabBar) {
  let result = clone(tabBar);
  result.list = tabBar.list.map(item => {
    return item.pagePath;
  });
  return result;
}
// 拼接完整的分包页路径
const repeatPattern = /\/{2,}/;
export function joinSubpackagePath(root, pagePath) {
  let path = root + '/' + pagePath;
  if (path.match(repeatPattern)) {
    path = path.replace(repeatPattern, '/');
  }
  return path;
}

function _normalizeRootPath(path) {
  if (!path.match(/\/$/)) {
    path += '/';
  }
  return path;
}
// 分解分包页路径
export function splitSubpackagePath(root, pagePath) {
  root = _normalizeRootPath(root);
  return pagePath.replace(root, '');
}
// 统一 subpackage.root 的格式
export function normalizeRootPath(path) {
  return _normalizeRootPath(path);
}
// 找到页面所属的分包
export function findSubpackageIndex(pageRoot, subpackages) {
  return subpackages.findIndex(item => {
    return item.root === pageRoot;
  });
}
